package net.oschina.esb.webmvc.filter;

import net.oschina.esb.core.AbstractSpringBootRegister;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Collections;

/**
 * 注册全局 Filter
 *
 * @author Arvin
 * @time 2017/12/6 9:15
 */
@Configuration
public class AutoWebmvcFilterSpringBootRegister extends AbstractSpringBootRegister {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, Environment environment, ApplicationContext applicationContext) {

        logger.info("注冊Filter: esbRootFilter");

        GenericBeanDefinition esbRootFilterBean = new GenericBeanDefinition();
        esbRootFilterBean.setBeanClass(EsbRootFilter.class);
        esbRootFilterBean.setLazyInit(false);

        registry.registerBeanDefinition("esbRootFilter", esbRootFilterBean);

        GenericBeanDefinition filterRegBean = new GenericBeanDefinition();
        filterRegBean.setBeanClass(FilterRegistrationBean.class);

        filterRegBean.getPropertyValues().addPropertyValue("filter", new RuntimeBeanReference("esbRootFilter"));
        filterRegBean.getPropertyValues().add("urlPatterns", Collections.singletonList("/*"));
        filterRegBean.getPropertyValues().add("name", "esbRootFilter");
        filterRegBean.getPropertyValues().add("order", 0);

        registry.registerBeanDefinition("esbRootFilterRegistrationBean", filterRegBean);
    }
}
